﻿namespace BEGDC.CC.Web.EZVisit
{
    #region Using Directives

    using System;
    using System.Data;
    using System.Linq;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using ASB.CC.ExcelTool;
    using ASBCC.Database.Entity;
    using ASBCC.Database.Service;
    using ASBCC.Workflow.Client;
    using UserControls;
    using Utility.Extensions;
    using Workflow;

    #endregion

    public partial class AdvancedSearch : BasePage
    {
        private string Sort
        {
            get
            {
                return Convert.ToString(this.ViewState["Sorting"]);
            }
            set
            {
                this.ViewState["Sorting"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.rblIsDomestic.SelectedValue = "all";
                this.Search(1);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.dgList.CurrentPageIndex = 0;
            this.Search(1);
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            //this.dgList.AllowPaging = false;

            //this.Search(1);

            //this.dgList.Columns[7].Visible = false;
            //this.dgList.Columns[8].Visible = true;

            //ExportDataGridToExcel.Export(this.Page, this.dgList, "EZVisitRequests.xls");

            //this.dgList.Columns[7].Visible = true;
            //this.dgList.Columns[8].Visible = false;

            new ExportEZVisitRequests().Export(this, this.GetSearchCondition());
        }

        protected void dgList_SortCommand(object source, DataGridSortCommandEventArgs e)
        {
            if (this.Sort.IndexOf(e.SortExpression) > -1 && this.Sort == e.SortExpression)
            {
                this.Sort = e.SortExpression + " desc";
            }
            else
            {
                this.Sort = e.SortExpression;
            }
            this.Search(1);
        }

        #region Search Helpers

        private void Search(int pageIndex)
        {
            EZVisitApplicationTableEntitySet applications = EZVisitApplicationManager.SelectByCondition(this.GetSearchCondition());

            DataTable dt = applications.Tables[0];

            foreach (DataRow row in dt.Rows.Cast<DataRow>().Where(row => row.IsNull("ProcessStatus")))
            {
                row["ProcessStatus"] = "Draft";
            }

            if (this.Sort.Length != 0)
            {
                dt.DefaultView.Sort = this.Sort;
            }

            this.dgList.DataSource = dt;
            this.dgList.DataBind();

            int count = dt.DefaultView.Count;
            this.SetPageCount(count, pageIndex);
        }

        private string GetSearchCondition()
        {
            var condition = new StringBuilder();

            condition.AppendFormat("IsEnabled = 1 and (readers like '%;{0};%' or requesterid = '{0}')", this.UserInfo.EmployeeID);

            if (this.txtEZVisitReqNo.Text.IsNotNullOrWhiteSpace())
            {
                condition.AppendFormat(" and EZVisitReqNo like '%{0}%'", this.txtEZVisitReqNo.Text.Trim().SanitizeSqlValue());
            }

            if (this.txtAppNo.Text.IsNotNullOrWhiteSpace())
            {
                condition.AppendFormat(" and AppNo like '%{0}%'", this.txtAppNo.Text.Trim().SanitizeSqlValue());
            }

            if (this.txtRequesterName.Text.IsNotNullOrWhiteSpace())
            {
                condition.AppendFormat(" and (RequesterNameCN like '%{0}%' or RequesterNameEN like '%{0}%')", this.txtRequesterName.Text.Trim().SanitizeSqlValue());
            }

            DateTime d;

            if (this.txtCreateAtFrom.Text.IsNotNullOrWhiteSpace() && DateTime.TryParse(this.txtCreateAtFrom.Text, out d))
            {
                condition.AppendFormat(" and SubmitDate >= '{0:MM/dd/yyyy}'", d);
            }

            if (this.txtCreateAtTo.Text.IsNotNullOrWhiteSpace() && DateTime.TryParse(this.txtCreateAtTo.Text, out d))
            {
                condition.AppendFormat(" and SubmitDate <= '{0:MM/dd/yyyy} 23:59:59'", d);
            }

            if (this.txtDeptHeadDateFrom.Text.IsNotNullOrWhiteSpace() && DateTime.TryParse(this.txtDeptHeadDateFrom.Text, out d))
            {
                condition.AppendFormat(" and LGDDate >= '{0:MM/dd/yyyy}'", d);
            }

            if (this.txtDeptHeadDateTo.Text.IsNotNullOrWhiteSpace() && DateTime.TryParse(this.txtDeptHeadDateTo.Text, out d))
            {
                condition.AppendFormat(" and LGDDate <= '{0:MM/dd/yyyy} 23:59:59'", d);
            }

            if (this.txtClosedDateFrom.Text.IsNotNullOrWhiteSpace() && DateTime.TryParse(this.txtClosedDateFrom.Text, out d))
            {
                condition.AppendFormat(" and PostCODPPHeadDate >= '{0:MM/dd/yyyy}'", d);
            }

            if (this.txtClosedDateTo.Text.IsNotNullOrWhiteSpace() && DateTime.TryParse(this.txtClosedDateTo.Text, out d))
            {
                condition.AppendFormat(" and PostCODPPHeadDate <= '{0:MM/dd/yyyy} 23:59:59'", d);
            }

            switch (this.ddlStatus.SelectedValue)
            {
                case "Draft":
                    condition.Append(" and (Status is null or Status = '')");
                    break;
                case "LGDApproved":
                    condition.AppendFormat(" and LGDDate is not null and ProcessStatus <> '{0}'", ProcessStatusConsts.End);
                    break;
                case "In Process":
                    string filter = string.Format("'{0}', '{1}'", ProcessStatusConsts.Discarded, ProcessStatusConsts.End);
                    condition.AppendFormat(" and LGDDate is null and ProcessStatus not in ({0})", filter);
                    break;
                case "Approved":
                    condition.AppendFormat(" and ProcessStatus = '{0}'", ProcessStatusConsts.End);
                    break;
                case "Rejected":
                    condition.AppendFormat(" and ProcessStatus = '{0}'", ProcessStatusConsts.Rejected);
                    break;
                case "Discarded":
                    condition.AppendFormat(" and ProcessStatus = '{0}'", ProcessStatusConsts.Discarded);
                    break;
            }

            if (!this.rblIsDomestic.SelectedValue.VariantEquals("all"))
            {
                condition.AppendFormat(" and IsDomestic = {0}", this.rblIsDomestic.SelectedValue);
            }

            if (this.txtContractNo.Text.IsNotNullOrWhiteSpace())
            {
                condition.AppendFormat(" and AppID in (select AppID from EZVisitContractItem where ContractNo like '%{0}%')", this.txtContractNo.Text.Trim().SanitizeSqlValue());
            }

            return condition.ToString();
        }

        #endregion

        #region Paging Events

        public void btnPageFirst_Click(object sender, ImageClickEventArgs e)
        {
            this.dgList.CurrentPageIndex = 0;
            this.Search(1);
        }

        public void btnPagePrev_Click(object sender, ImageClickEventArgs e)
        {
            if (this._CurrentPageIndex == 1)
            {
                return;
            }
            this.dgList.CurrentPageIndex = this._CurrentPageIndex - 2;
            this.Search(this._CurrentPageIndex - 1);
        }

        public void btnPageNext_Click(object sender, ImageClickEventArgs e)
        {
            if (this._CurrentPageIndex == this._PageCount)
            {
                return;
            }
            this.dgList.CurrentPageIndex = this._CurrentPageIndex;
            this.Search(this._CurrentPageIndex + 1);
        }

        public void btnPageLast_Click(object sender, ImageClickEventArgs e)
        {
            this.dgList.CurrentPageIndex = this._PageCount - 1;
            this.Search(this._PageCount);
        }

        public void btnGotoPage_Click(object sender, ImageClickEventArgs e)
        {
            if (this.txtPage.Text == string.Empty)
            {
                this.txtPage.Text = "1";
            }
            int gotopage = 1;
            try
            {
                gotopage = Convert.ToInt32(this.txtPage.Text);
            }
            catch
            {
            }
            int currentpage = 0;

            if (gotopage >= this._PageCount)
            {
                gotopage = this._PageCount;
                currentpage = gotopage - 1;
                if (currentpage < 0)
                {
                    currentpage = 0;
                }
            }
            else if (gotopage <= 0)
            {
                gotopage = 1;
            }
            else
            {
                currentpage = gotopage - 1;
            }

            this.dgList.CurrentPageIndex = currentpage;

            this.Search(gotopage);

            this.txtPage.Text = string.Empty;
        }

        #endregion

        #region Page Navigation Properties

        private int _PageCount
        {
            get
            {
                return Convert.ToInt32(this.ViewState["PageCount"]);
            }
            set
            {
                this.ViewState["PageCount"] = value;
            }
        }

        private int _CurrentPageIndex
        {
            get
            {
                return Convert.ToInt32(this.ViewState["CurrentPageIndex"]);
            }
            set
            {
                this.ViewState["CurrentPageIndex"] = value;
            }
        }

        private int _RowCount
        {
            get
            {
                return Convert.ToInt32(this.ViewState["RowCount"]);
            }
            set
            {
                this.ViewState["RowCount"] = value;
            }
        }

        private void SetPageNavi(int newPage)
        {
            if (newPage <= 1)
            {
                this.btnPageFirst.ImageUrl = WebUtility.Path + "/images/pg_first_inact.gif";
                this.btnPagePrev.ImageUrl = WebUtility.Path + "/images/pg_pre_inact.gif";
                this.btnPageFirst.Attributes["disabled"] = "true";
                this.btnPagePrev.Attributes["disabled"] = "true";
            }
            else
            {
                this.btnPageFirst.ImageUrl = WebUtility.Path + "/images/pg_first.gif";
                this.btnPagePrev.ImageUrl = WebUtility.Path + "/images/pg_pre.gif";
                this.btnPageFirst.Attributes.Remove("disabled");
                this.btnPagePrev.Attributes.Remove("disabled");
            }

            if (newPage >= this._PageCount)
            {
                this.btnPageNext.ImageUrl = WebUtility.Path + "/images/pg_next_inact.gif";
                this.btnPageLast.ImageUrl = WebUtility.Path + "/images/pg_last_inact.gif";
                this.btnPageNext.Attributes["disabled"] = "true";
                this.btnPageLast.Attributes["disabled"] = "true";
            }
            else
            {
                this.btnPageNext.ImageUrl = WebUtility.Path + "/images/pg_next.gif";
                this.btnPageLast.ImageUrl = WebUtility.Path + "/images/pg_last.gif";
                this.btnPageNext.Attributes.Remove("disabled");
                this.btnPageLast.Attributes.Remove("disabled");
            }

            this.lblCurrentPageIndex.Text = newPage.ToString();
            this.lblPageCount.Text = this._PageCount.ToString();
            this.lblRecordCount.Text = this._RowCount.ToString();
        }

        private void SetPageCount(int count, int pageIndex)
        {
            if (count > 0)
            {
                this._RowCount = count;
                this._PageCount = count / this.dgList.PageSize;
                if (count % this.dgList.PageSize > 0)
                {
                    this._PageCount++;
                }

                this._CurrentPageIndex = pageIndex;
                this.SetPageNavi(pageIndex);
            }
            else
            {
                this._RowCount = count;
                this._PageCount = count;
                this._CurrentPageIndex = 0;
                this.SetPageNavi(0);
            }
        }

        #endregion
    }
}